package com.example.basic.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.util.ListUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.function.Consumer;

/**
 * @author mjw
 * @date 2022/12/23
 */
public class CommonReadListener<T> extends AnalysisEventListener<T> {

    public static final Logger LOGGER = LoggerFactory.getLogger(CommonReadListener.class);

    /**
     * 每隔100条存储数据库，实际可用300条，然后清理list，方便内存回收
     */
    public static final int BATCH_COUNT = 100;
    private List<T> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    private final Consumer<List<T>> consumer;

    public CommonReadListener(Consumer<List<T>> consumer) {
        this.consumer = consumer;
    }

    /**
     * 每一条数据解析的时候都会调用这个方法
     * @param data
     * @param context
     */
    @Override
    public void invoke(T data, AnalysisContext context) {
        cachedDataList.add(data);
        if (cachedDataList.size() >= BATCH_COUNT) {
            consumer.accept(cachedDataList);
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        if (CollectionUtils.isNotEmpty(cachedDataList)) {
            consumer.accept(cachedDataList);
        }
    }

}

